import { Button, Collapse, Toast } from 'antd-mobile';
import { useState, useEffect, useRef } from 'react';
import { fetchList } from './server'
import { getQueryParams } from '../../utils'
import styles from './index.less'
import QRCode from 'qrcode'


const Todo = () => {
  const handler = useRef()
  const [list, setList] = useState([]);


  const getImages = async (item, key) => {
    const url = `http://47.108.248.39/user/index.html?api_key=${key}&id=${item.id}`
    return QRCode.toDataURL(url)
  }

  const addQrcode = (list, key) => {
    let res = []
    list.forEach(async (item) => {
      const code = await getImages(item, key)
      res.push({ ...item, qrcode: code })
    })
    return res
  }

  const fetchData = async () => {
    const url = location.href;
    const { api_key } = getQueryParams(url)
    const local_api_key = window.localStorage.getItem('api_key')
    if (!api_key && !local_api_key) {
      return Toast.show({
        icon: 'fail',
        content: '请扫码获取权限',
      })
    }
    if (api_key && local_api_key !== api_key) {
      window.localStorage.setItem('api_key', api_key)
    }
    handler.current = Toast.show({
      icon: 'loading',
      content: '加载中…',
      maskClickable: false,
      duration: 0,
    })
    const key = api_key || local_api_key
    const res = await fetchList(key);
    const data = addQrcode(res, key)
    setList(data);
    handler.current?.close()
  }

  const submit = async () => {
    try {
      await fetchData()
      handler.current?.close()
    } catch (error) {
      handler.current?.close()
    }
  }

  useEffect(() => {
    fetchData()
  }, [])
  return (
    <div className={styles.box}>
      <div className={styles.btn} >
        <Button color='primary' onClick={submit}>刷新评论列表</Button>
      </div>
      <Collapse>
        {
          list?.map((item, index) => (
            <Collapse.Panel key={index} title={item.comment.substring(0, 8) + '...'}>
              <div className={styles.wrap}>
                <div className={styles.content}>{item.comment}</div>
                <div className={styles.imgs}>
                  <img src={item.qrcode} alt="" />
                </div>
              </div>
            </Collapse.Panel>
          ))
        }
      </Collapse>
    </div>
  );
};

Todo.title = 'TOTO';
Todo.icon = 'toto-icon';
Todo.badge = '5';
export default Todo;
